/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stm32f1xx_hal.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define OK 1  				//系统运作正常
#define ERROR1 2  				//系统错误1
#define ERROR2 3  				//系统错误2

#define RX_BUFFER_SIZE  128    // 缓冲区大小
#define PACKET_END_CHAR 0x55   // 数据包结束标志
#define FIXED_PACKET_LEN 23    // 固定长度数据包长度
#define  USE_END_CHAR_MODE 0

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
uint16_t tickCount = 0;
uint16_t timeDelay = 0;
uint16_t system = 0;
// 接收缓冲区和状态变量
uint8_t rx_buffer[RX_BUFFER_SIZE];  // 数据缓冲区
uint8_t rx_buffer2[RX_BUFFER_SIZE];
uint8_t usart2_tx_buffer[20];
uint8_t iic_tx_buffer[20];
uint8_t I2C_RXBuff[16];
uint8_t error_buff[2] = { 0xFF, 0xEE };			  // 数据缓冲区
uint8_t rx_len = 0;                // 当前接收长度
uint8_t rx_len2 = 0;
uint8_t rx_complete = 0;            // 接收完成标志（0：未完成，1：完成）
uint8_t rx_complete2 = 0;
FlagStatus Command = RESET;

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
void SWIRE_TX(uint8_t times, uint8_t spend);
void delay_us(uint16_t us);
void RUN_LED(uint16_t times);
void System_state(uint8_t state);
void Uart2_Uart1(void);
void I2C_Write(uint16_t mem_addr, uint8_t *data, uint16_t size);
void I2C_Read(uint8_t mem_addr, uint8_t reg_addr, uint8_t *data, uint16_t len);
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

	/* USER CODE BEGIN 1 */

	/* USER CODE END 1 */

	/* MCU Configuration--------------------------------------------------------*/

	/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	HAL_Init();

	/* USER CODE BEGIN Init */

	/* USER CODE END Init */

	/* Configure the system clock */
	SystemClock_Config();

	/* USER CODE BEGIN SysInit */

	/* USER CODE END SysInit */

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_I2C1_Init();
	MX_USART1_UART_Init();
	MX_TIM4_Init();
	MX_TIM3_Init();
	MX_USART2_UART_Init();
	/* USER CODE BEGIN 2 */
	HAL_TIM_Base_Start_IT(&htim3);								//开启滴答计时器TIM3
	system = OK;												//初始化完成，系统OK
	HAL_UART_Receive_IT(&huart1, &rx_buffer[rx_len], 1);		// 启动中断接收（每次接收1个字节）
	HAL_UART_Receive_IT(&huart2, &rx_buffer2[rx_len2], 1);

	/* USER CODE END 2 */

	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1)
	{

		System_state(system);			//系统的状态灯
		Uart2_Uart1();					//串口2透传串口1

		//HAL_UART_Transmit(&huart1, (uint8_t*)rx_buffer, strlen(rx_buffer), HAL_MAX_DELAY);
		if (Command)
		{

			if (rx_buffer[0] == 0xAA)				//判断数据包头是否正确
			{

				switch (rx_buffer[1])				//判断包头是什么协议

				{
				case 0x01:										//I2C

					if (rx_buffer[3]==0)							//判断是读还是写
					{
						//写I2C内容
						for (uint8_t i = 0; i < 16; i++)
						{
							iic_tx_buffer[i] = rx_buffer[i + 5];

						}
						//发送I2C内容
						I2C_Write(rx_buffer[4], iic_tx_buffer, rx_buffer[2]);
					} else if(rx_buffer[3]==1)
					{
						//读I2C内容

						I2C_Read(rx_buffer[4], rx_buffer[5], I2C_RXBuff, rx_buffer[2]);
						HAL_UART_Transmit(&huart1, I2C_RXBuff, rx_buffer[2], 100);


					}

					break;

				case 0x02:										//Uart

					for (uint8_t i = 0; i < 16; i++)						//将数据转存到Usart2_TX_Buff
					{
						usart2_tx_buffer[i] = rx_buffer[i + 6];
					}

					HAL_UART_Transmit(&huart2, usart2_tx_buffer, rx_buffer[2], 100);		//通过串口2发送，发送长度通过协议Byte=2控制

					break;
				case 0x03:						//Swire
					SWIRE_TX(rx_buffer[2], 0);								//一线通讯，SWIRE_TX(发送几个脉冲, 脉冲的速度，0=最快，以此类推);
					break;
				}
			} else
			{
				HAL_UART_Transmit(&huart1, &error_buff[0], 1, 100);						//返回错误信息0XFF为包络头错误

			}

			Command = RESET;
			// 重置缓冲区和标志，准备下一次接收
			memset(rx_buffer, 0, RX_BUFFER_SIZE);

			rx_len = 0;
			rx_complete = 0;
			// 重新启动中断接收
			HAL_UART_Receive_IT(&huart1, &rx_buffer[rx_len], 1);

		}

		/* USER CODE END WHILE */

		/* USER CODE BEGIN 3 */
	}
	/* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
	RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
	RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };

	/** Initializes the RCC Oscillators according to the specified parameters
	 * in the RCC_OscInitTypeDef structure.
	 */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
	RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
	{
		Error_Handler();
	}

	/** Initializes the CPU, AHB and APB buses clocks
	 */
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
	{
		Error_Handler();
	}
}

/* USER CODE BEGIN 4 */
void I2C_Write(uint16_t mem_addr, uint8_t *data, uint16_t size)
{

	HAL_I2C_Master_Transmit(&hi2c1, mem_addr, data, size, 100);
	HAL_Delay(5);  // 等待EEPROM写入完成
}
void I2C_Read(uint8_t mem_addr, uint8_t reg_addr, uint8_t *data, uint16_t len)
{
	HAL_I2C_Mem_Read(&hi2c1, mem_addr, reg_addr,
	I2C_MEMADD_SIZE_8BIT, data, len, 100);
}

void SWIRE_TX(uint8_t times, uint8_t spend)
{

	times = times * 2;

	for (uint8_t i = 0; i < times; i++)
	{
		HAL_GPIO_TogglePin(SWIRE_GPIO_Port, SWIRE_Pin);
		delay_us(spend);
	}

}

void RUN_LED(uint16_t times)				//LED灯1S闪光几次
{
	times = 1000 / times;
	if (tickCount >= times)
	{
		// 翻转LED引脚电平
		HAL_GPIO_TogglePin(RUN_LED_GPIO_Port, RUN_LED_Pin);
		tickCount = 0;
		timeDelay++;
	}

}

// us 级延迟函数
void delay_us(uint16_t us)
{
	__HAL_TIM_SET_COUNTER(&htim4, 0);   // 计数器清零
	HAL_TIM_Base_Start(&htim4);         // 启动 TIM4
	while (__HAL_TIM_GET_COUNTER(&htim4) < us); // 等待计数到目标值
	HAL_TIM_Base_Stop(&htim4);          // 停止 TIM4（可选）
}

// 定时器更新中断回调函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim->Instance == htim3.Instance)
	{
		tickCount++;		//中断时间为1ms

	}
}
//系统状态灯
void System_state(uint8_t state)
{
	switch (state) {
	case 1:
		RUN_LED(1);					//正常运行1S闪一次

		break;

	case 2:
		RUN_LED(4);					//错误1S闪三次
		if (state >= 2)
		{
			if (timeDelay > 5)
			{
				HAL_Delay(1000);
				timeDelay = 0;
			}
		}
		break;
	case 3:
		RUN_LED(4);					//错误1S闪4次
		if (state >= 2)
		{
			if (timeDelay > 7)
			{
				HAL_Delay(1000);
				timeDelay = 0;
			}
		}
		break;
	}
}
//串口2转发数据到串口1

void Uart2_Uart1(void)
{
	if (rx_complete2)
	{
		HAL_UART_Transmit(&huart1, rx_buffer2, rx_len2, 100);
		memset(rx_buffer2, 0, RX_BUFFER_SIZE);							//清除寄存器
		rx_complete2 = 0;												//清除状态位
		rx_len2 = 0;

		HAL_UART_Receive_IT(&huart2, &rx_buffer2[rx_len2], 1);
	}

}

//串口回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if (huart->Instance == USART1)   // 判断是USART1
	{
#if USE_END_CHAR_MODE
	if (rx_buffer[rx_len] == PACKET_END_CHAR || rx_len >= RX_BUFFER_SIZE - 1)
	{
		rx_complete = 1;  // 标记接收完成
		Command = SET;
	} else
	{
		rx_len++;  // 未完成则继续接收下一个字节
		// 启动下一次中断接收
		HAL_UART_Receive_IT(&huart1, &rx_buffer[rx_len], 1);
	}
#else
		rx_len++;
		if (rx_len >= FIXED_PACKET_LEN || rx_len >= RX_BUFFER_SIZE - 1)
		{
			rx_complete = 1;  // 标记接收完成
			Command = SET;
		} else
		{
			// 启动下一次中断接收
			HAL_UART_Receive_IT(&huart1, &rx_buffer[rx_len], 1);
		}
#endif

	}
	if (huart->Instance == USART2)   // 判断是USART1
	{
		rx_len2++;
		if (rx_len2 >= FIXED_PACKET_LEN || rx_len2 >= RX_BUFFER_SIZE - 1)
		{
			rx_complete2 = 1;  // 标记接收完成
		} else
		{
			// 启动下一次中断接收
			HAL_UART_Receive_IT(&huart2, &rx_buffer2[rx_len2], 1);
		}

	}

}

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
	/* USER CODE BEGIN Error_Handler_Debug */
	/* User can add his own implementation to report the HAL error return state */
	__disable_irq();
	while (1)
	{
	}
	/* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
 ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
